package Controller.Announcement;

import Models.dao.AnnouncementDao;
import Models.enity.AdminUser;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/announcement/create")
public class AnnouncementCreateController extends HttpServlet {
    private static String PublicPath = "/WEB-INF/views";
    private AnnouncementDao announcementDao = new AnnouncementDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(PublicPath + "/announcement/create.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String content = req.getParameter("content").trim();
        AdminUser user = (AdminUser) req.getSession().getAttribute("user");
        String department = user.getDepartment();
        Date date = new Date( );
        SimpleDateFormat ft = new SimpleDateFormat ("yyyy.MM.dd hh:mm:ss");
        String created_at = ft.format(date);
        int tmp = announcementDao.insert(content,department,created_at);
        if (tmp != -1){
            resp.sendRedirect("/announcement");
        }else {
            req.setAttribute("message","公告新建错误，请重试！");
            req.getRequestDispatcher(PublicPath + "/announcement/announcement.jsp").forward(req,resp);
        }
    }
}
